import 'dart:async';

import 'package:amap_plugin/src/models/location.dart';
import 'package:flutter/services.dart';
import 'package:location_permissions/location_permissions.dart';

class AmapLocation {
  static AmapLocation _instance;
  final MethodChannel _locationMethodChannel;
  final EventChannel _locationEventChannel;
  Stream<Location> _onLocationChanged;

  factory AmapLocation() {
    if (_instance == null) {
      _instance = AmapLocation.private(
          const EventChannel("location_event_channel"),
          const MethodChannel("location_method_channel"));
    }
    return _instance;
  }

  AmapLocation.private(this._locationEventChannel, this._locationMethodChannel);

  ///订阅定位变更信息
  Stream<Location> get onLocationChanged {
    if (_onLocationChanged == null) {
      _onLocationChanged =
          _locationEventChannel.receiveBroadcastStream().map((event){
            return Location.fromJson(event);
          }
           
           );
    }
    return _onLocationChanged;
  }

  ///获取位置信息
  Future<void> get startLocation async {
    PermissionStatus permissionStatus =
        await LocationPermissions().requestPermissions();
    if (permissionStatus == PermissionStatus.granted) {
      _locationMethodChannel.invokeMethod("startLocation");
    } else {
      throw '未授权';
    }
  }

  ///停止监听位置信息
  Future<void> get stopLocation async =>
      _locationMethodChannel.invokeMethod("stopLocation");

  ///获取定位信息
  Future<Location> get getLocation async {
    var result = await _locationMethodChannel.invokeMethod("getLocation");
    return Location.fromJson(result);
  }
}
